package cn.larry.common.utils;

import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 2025/2/15 09:58
 *
 * @Version 2.0
 */
public class DeepSeekUtils {

    public static Integer parentMessageId = 2;
    public static String CHAT_SESSION_ID = "7fa9a44a-abf7-4226-9b7f-6894dca0042c";

    public static void main(String[] args) throws Exception {
        run("新余今天天气温度多少?", parentMessageId);
    }

    /**
     * 启动执行
     * @param problemMsg
     * @param parentMessageId
     * @throws Exception
     */
    public static void run(String problemMsg, Integer parentMessageId) throws Exception {
        System.out.println(parentMessageId+"");
        runPost(problemMsg, parentMessageId);
    }

    /**
     * 配置请求头信息
     */
    private static void setRequestProperty(HttpURLConnection connection){

        // 设置请求头部信息，可固定
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36");
        connection.setRequestProperty("cookie", "Hm_lvt_fb5acee01d9182aabb2b61eb816d24ff=1739167573; smidV2=202502101406230f12e79727e28c7d50873a2e6fc5ae91005c585bc977d4c70; .thumbcache_6b2e5483f9d858d7c661c5e276b6a6ae=Jbv7QpkwihsWFsWuUfolQFBTQkHYt/nZXeb0t3umok8025kXg4FOvrGw/KFI+Q/ebn9sIRQ7wzn4006KHchEkg%3D%3D; intercom-device-id-guh50jw4=c437d829-6dfb-4e8c-a703-b7a8a1304a25; HWWAFSESTIME=1739500717453; HWWAFSESID=f69c39e5914602a4787; ds_session_id=60ae05bba85c4cf69da6e32892992b33; intercom-session-guh50jw4=ck02dXZpOERYZFJMNXBlcjdKK3RSZHVJa3UwTFlrOVpRTE5uOS82djV6cEVTMk5HdHZqOU9VYmRrZDkrek9VMGF0Mk52c3FTNW1TaFYzNWE0MUVXZGVkaHBPVE9XT3pEOVdSRWZXMStpb2c9LS1xZFcyN1NCWU9TWm8xbXl0V1ZYNXdBPT0=--376a1e4c56578796d4b559632051dfd7e558a08e");// 得跟上述'chat_session_id'一致获取的内容，一套信息
        connection.setRequestProperty("authorization", "Bearer zg3BvcPxBOKGxwKfvX5uBWEJ8xfVr6z9CWVP0sg8MszcA8M0bYQsz2ndwA2YzC+/");// 得跟上述'chat_session_id'一致获取的内容，一套信息
        connection.setRequestProperty("x-ds-pow-response", "eyJhbGdvcml0aG0iOiJEZWVwU2Vla0hhc2hWMSIsImNoYWxsZW5nZSI6IjlhYmYwNzM4NDYwODE4MWI5ZTZmODk4M2Y1M2QyZmM5ZjAyNWNjZGY3ZDhmOTM3ZDRkOWY0ZjhiZTk2M2ZkMDkiLCJzYWx0IjoiY2ZlYmY3NjJjOWJiMTc2YzZiYjIiLCJhbnN3ZXIiOjgzNjk4LCJzaWduYXR1cmUiOiIxZmJlOWI4OTY2YTQ0ZDExYWMxYzQ1Mjk3NDg4NDBlYzA2MWE3NjRjNDRhMzJlZjg1MDRiOWU5Y2QxNWRmOWE0IiwidGFyZ2V0X3BhdGgiOiIvYXBpL3YwL2NoYXQvY29tcGxldGlvbiJ9");// 可有可无，防止频繁的报错，建议加上；得跟上述'chat_session_id'一致获取的内容，一套信息

    }

    /**
     *
     * @param problemMsg    消息内容
     * @param parentMessageId   响应的消息ID
     * @throws Exception
     */
    public static void runPost(String problemMsg, Integer parentMessageId) throws Exception {
        String url = "https://chat.deepseek.com/api/v0/chat/completion";// 固定请求地址

        String jsonBody = "{" +
                "  \"chat_session_id\": \""+CHAT_SESSION_ID+"\"," +// chat_session_id，网页端deepseek的会话ID,一致有效（https://chat.deepseek.com/a/chat/s/432f16db-3a93-4cae-aa8d-f273686c603X）
                "  \"parent_message_id\": " + parentMessageId + "," +// 响应的消息ID，不建议一直使用同一个；同一个用久了会报错
                "  \"prompt\": \"" + problemMsg + "\"," +// 消息内容
                "  \"ref_file_ids\": []," +
                "  \"thinking_enabled\": false," +// 深度思考R1选项
                "  \"search_enabled\": true" +// 联网搜索选项
                "}";

        JSONObject reqJson = new JSONObject();
        reqJson.put("chat_session_id",CHAT_SESSION_ID);// chat_session_id，网页端deepseek的会话ID,一致有效（https://chat.deepseek.com/a/chat/s/{CHAT_SESSION_ID}}）
        reqJson.put("parent_message_id",parentMessageId);// 响应的消息ID，不建议一直使用同一个；同一个用久了会报错
        reqJson.put("prompt",problemMsg);// 消息内容
        reqJson.put("ref_file_ids", null);
        reqJson.put("thinking_enabled",false);// 深度思考R1选项
        reqJson.put("search_enabled",true);// 联网搜索选项

        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为 POST
        connection.setRequestMethod("POST");

        setRequestProperty(connection);

        // 启用输出流，发送请求体数据
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(jsonBody.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();

        // 获取响应
        int responseCode = connection.getResponseCode();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        System.out.println("Response Code: " + responseCode);
        System.out.println("Response Body: " + response.toString());
        if (200 - responseCode != 0)
            return;
        String respBody = response.toString();// 返回的报文

        if (respBody.contains("invalid chat session id or parent message id") || respBody.contains("parent message id role must be assistant"))
            runPost(problemMsg, parentMessageId++);
        else if (respBody.contains("Invalid PoW response")){
            Thread.sleep(1000);
            runPost(problemMsg, parentMessageId++);
        }
//
//        } else if ("parent_message_id 无效".equals(textSb.toString())) {// 处理返回异常

        String[] split = respBody.split("data: ");
        StringBuffer textSb = new StringBuffer();
        for (String str : split) {
//            System.out.println(str);
            if (StringUtils.isEmpty(str))
                continue;
            try {
                JSONObject jsonObject = JSONObject.parseObject(str);
                Integer messageId = jsonObject.getInteger("message_id");// 下次请求的'parent_message_id'值
                Object o = jsonObject.getJSONArray("choices").get(0);
                JSONObject choices = JSONObject.from(JSONObject.parseObject(o.toString()));
                JSONObject delta = choices.getJSONObject("delta");
                String content = delta.getString("content");
                if (StringUtils.isEmpty(content))
                    continue;
                textSb.append(content);
            } catch (Exception e) {
            }
        }
//        if ("服务器繁忙，请稍后再试。".equals(textSb.toString())) {// 处理返回异常
//
//        } else if ("parent_message_id 无效".equals(textSb.toString())) {// 处理返回异常
//
//        } else
        System.out.println(textSb.toString());


    }

}
